package com.energy.analysis.comm.base;

import com.energy.analysis.comm.page.Page;
import com.energy.analysis.comm.utils.DateUtils;
import com.energy.analysis.comm.utils.DownloadFileUtil;
import com.energy.analysis.comm.utils.StringUtils;
import com.energy.analysis.comm.utils.excel.ExcelExportUtil;
import com.energy.analysis.comm.utils.excel.dto.ExcelTemplateType;
import com.energy.analysis.comm.utils.excel.factory.ExcelXmlModelFactory;
import com.energy.analysis.sys.entity.Menu;
import com.energy.analysis.sys.entity.MenuDto;
import com.energy.analysis.sys.entity.OprInfo;
import com.energy.analysis.sys.service.MenuService;
import com.energy.analysis.weather.entity.WeatherData;
import com.energy.analysis.weather.service.WeatherService;
import com.google.gson.reflect.TypeToken;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author A18ccms a18ccms_gmail_com
 * @ClassName: BaseController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2015年8月27日 下午12:48:57
 */
public abstract class BaseController<T extends BaseEntity> extends
        AbstractController {

    public static final String CUR_OPR_SESSION_KEY = "currOprInfo";
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private MenuService menuService;
    @Autowired
    private WeatherService weatherService;

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public void initPage(Page<T> page, T entity) {
        page.setEntity(entity);
    }

    public void initPage(Page<T> page) {
        BufferedReader in = null;
        String line = null;
        try {
            in = request.getReader();
            StringBuilder sb = new StringBuilder();
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            Map<String, Object> params = StringUtils.getGson().fromJson(sb.toString(), new TypeToken<Map<String, Object>>() {
            }.getType());
            if (params != null) {
                if (params.get("limit") != null && params.get("offset") != null) {
                    page.setLimit((int) (Double.parseDouble(params.get("limit").toString())));
                    page.setOffset((int) (Double.parseDouble(params.get("offset").toString())));
                }
                page.setParams(params);
                // 当前操作员登录机构
                page.getParams().put("currOrgId", getCurrOprInfo().getOrgId());
            }
        } catch (IOException e) {
            logger.error("读取参数异常", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 获取当前session中登陆操作员信息
     *
     * @param @return 设定文件
     * @return OprInfo 返回类型
     * @throws
     * @Title: getCurrOprInfo
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public OprInfo getCurrOprInfo() {
        return (OprInfo) SecurityUtils.getSubject().getPrincipal();
    }

    /**
     * @param @param entity 设定文件
     * @return void 返回类型
     * @throws
     * @Title: initEntity
     * @Description: TODO(初始化entity相关数据)
     */
    public void initEntity(T entity) {
        initCrt(entity);
        initUpt(entity);
    }

    public void initCrt(T entity) {
        entity.setCrtDt(DateUtils.getYmdDate());
        entity.setCrtTm(DateUtils.getHmsTime());
    }

    public void initUpt(T entity) {
        entity.setUptDt(DateUtils.getYmdDate());
        entity.setUptTm(DateUtils.getHmsTime());
    }

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
                                                 HttpServletResponse arg1) throws Exception {
        return null;
    }

    /**
     * @param response
     * @param exportList      导出的数据
     * @param excelModelName  与excel_model中的对应的modelId名称
     * @param fileName        生成的文件名称
     * @param sheetName       生成sheet名称
     */
    protected void exportFile(HttpServletResponse response, List<Map<String, Object>> exportList, String excelModelName, String fileName, String sheetName) {
        ExcelTemplateType excelTemplate = ExcelXmlModelFactory.getInstance().getExcelInfo(excelModelName);
        // 2.创建excel工具对象
        ExcelExportUtil excelExport = new ExcelExportUtil(excelTemplate);
        try {
            // 3.根据模版创建HSSFWorkbook对象
            excelExport.createWorkBookByTemplate(sheetName);
            excelExport.writeQueryResult(exportList);
            HSSFWorkbook hSSFWorkbook = excelExport.getHSSFWorkbook();
            DownloadFileUtil.getInstance().downLoadExcel(hSSFWorkbook, fileName, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void pageInitToSession(HttpSession session) {
        menuAddSession(session);
        weatherAddSession(session);
    }

    protected List<MenuDto> getMenus() {
        OprInfo oprInfo = getCurrOprInfo();
        List<Menu> menus = menuService.getMenus(oprInfo.getRoles());
        // 配置前端页面的menu显示
        menus.remove(0);

        List<MenuDto> results = new ArrayList<>();
        MenuDto lastNoLeafMenuDto = null;
        for (Menu menu : menus) {
            MenuDto menuDto = new MenuDto(menu);
            if (menu.isLeaf()) {
                if (lastNoLeafMenuDto == null) {// 没有父节点，直接是子节点
                    results.add(menuDto);
                } else {
                    lastNoLeafMenuDto.addSubMenu(menuDto);
                }
            } else {
                lastNoLeafMenuDto = menuDto;
                results.add(lastNoLeafMenuDto);
            }
        }
        return results;
    }

    private void menuAddSession(HttpSession session) {
        // 从session中获取菜单展示
        String menuHtml = (String) session.getAttribute("menuHtml");
        if (menuHtml == null || menuHtml.length() < 1) {
            OprInfo oprInfo = getCurrOprInfo();
            String main_url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
            /* 获取登陆菜单 */
            List<Menu> menus = menuService.getMenus(oprInfo.getRoles());
            // 配置前端页面的menu显示
            menus.remove(0);
            StringBuilder sb = new StringBuilder("");
            int i = 0;
            // 判断首页显示
            Menu firstMenu = menus.get(0);
            if (firstMenu != null && "home".equals(firstMenu.getMenuCode())) {
                sb.append("<li id='home'><a href='" + main_url + firstMenu.getMenuUrl() + "'><i class='fa fa-home'></i >" + firstMenu.getMenuName() + "</a></li>");
                i = 1;
            }
            for (; i < menus.size(); i++) {
                Menu menu = menus.get(i);
                if ("0".equals(menu.getIsLeaf())) { // 根节点
                    sb.append(" <li > ");
                    sb.append(firstLevelMenu(menu));
                    sb.append(" <ul class='submenu'> ");
                } else if ("1".equals(menu.getIsLeaf())) {// 叶节点
                    sb.append(secondLevelMenu(menu, main_url));
                    if (i + 1 == menus.size() || "0".equals(menus.get(i + 1).getIsLeaf())) { // 判断是否为当前叶节点的结尾
                        sb.append("</ul></li>");
                    }
                }
            }
            menuHtml = sb.toString();
            session.setAttribute("menuHtml", menuHtml);
        }
    }

    private String firstLevelMenu(Menu menu) {
        return "<a href=\"#\" class=\"dropdown-toggle\">\n" +
                "    <i class=\"" + menu.getIcon() + " normal\"></i>\n" +
                "    <span class=\"menu-text normal\"> " + menu.getMenuName() + " </span>\n" +
                "    <b class=\"arrow fa fa-angle-right normal\"></b>\n" +
                "</a>";
    }

    private String secondLevelMenu(Menu menu, String baseUrl) {
        return  "<li><a href=\"" + baseUrl + menu.getMenuUrl() + "\">\n" +
                //"    <i class=\"fa fa-caret-right\"></i>\n" +  //这里的向右一个箭头，去掉了，双层向右箭头 fa-angle-double-right
                "    <i class=\"fa\"></i>\n" +
                "    <span class=\"menu-text\">" + menu.getMenuName() + "</span>\n" +
                "</a></li>";
    }

    //获取天气信息
    public void weatherAddSession(HttpSession session) {
        String weatherHtml = (String) session.getAttribute("weatherHtml");
        if (weatherHtml == null || weatherHtml.length() < 1) {
            //获取当前天气状况
            WeatherData weatherData = weatherService.findWeatherCurr(DateUtils.getYmdDate());
            if (weatherData != null) {
                StringBuilder sb = new StringBuilder();
                sb.append("<b>今日:</b> " + DateUtils.getDayWeek());
                sb.append("&nbsp;&nbsp;哈尔滨  " + weatherData.getTeC1());
                sb.append("&nbsp;&nbsp;<font color='red'>" + weatherData.getTeH() + "℃</font>~ <font color='blue'>" + weatherData.getTeL() + "℃ </font>");
                sb.append(weatherData.getTeWd1() + "&nbsp;&nbsp;" + weatherData.getTeWe1());
                session.setAttribute("weatherHtml", sb.toString());
            }
        }
    }
}
